package com.ytjj.qmyx.mall.controller;

import cn.hutool.json.JSONObject;
import com.gexin.fastjson.JSON;
import com.github.pagehelper.util.StringUtil;
import com.ytjj.common.api.CommonResult;
import com.ytjj.common.api.ResultCode;
import com.ytjj.common.constants.SysConfigConstants;
import com.ytjj.common.controller.BaseController;
import com.ytjj.common.model.UsersResponse;
import com.ytjj.common.service.RedisService;
import com.ytjj.common.utils.*;
import com.ytjj.common.utils.qqzengip.IpSearch;
import com.ytjj.qmyx.mall.config.SupplyApiConfig;
import com.ytjj.qmyx.mall.constants.DynamicConstant;
import com.ytjj.qmyx.mall.constants.ExpireTimeConstant;
import com.ytjj.qmyx.mall.constants.IsCollectConstant;
import com.ytjj.qmyx.mall.constants.RedisConstants;
import com.ytjj.qmyx.mall.enums.ActivityTypeEnums;
import com.ytjj.qmyx.mall.enums.DynamicStatusEnums;
import com.ytjj.qmyx.mall.enums.ProductStatusEnums;
import com.ytjj.qmyx.mall.mapper.*;
import com.ytjj.qmyx.mall.model.*;
import com.ytjj.qmyx.mall.model.dto.ProductDto;
import com.ytjj.qmyx.mall.model.dto.RecordSubsidyDataDto;
import com.ytjj.qmyx.mall.model.dto.SubsidyDataDto;
import com.ytjj.qmyx.mall.model.esmodel.ProductActivityEsDto;
import com.ytjj.qmyx.mall.model.esmodel.ProductEsDto;
import com.ytjj.qmyx.mall.model.request.*;
import com.ytjj.qmyx.mall.model.response.*;
import com.ytjj.qmyx.mall.service.*;
import com.ytjj.qmyx.mall.utils.AdvertReportUtil;
import com.ytjj.qmyx.mall.utils.ArrayUtil;
import com.ytjj.qmyx.mall.utils.ProductRecordUtil;
import com.ytjj.qmyx.users.client.UsersClient;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.data.elasticsearch.core.query.SearchQuery;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import static org.elasticsearch.index.query.QueryBuilders.multiMatchQuery;
import static org.elasticsearch.index.query.QueryBuilders.termQuery;

/**
 * 商品控制器
 *
 *
 * @version 1.0
 *
 */
@RestController
@RequestMapping("/product")
@Slf4j
@RefreshScope
@EnableAsync
public class ProductController extends BaseController {

    private final ProductService productService;
    private final UsersClient usersClient;

    @Autowired
    private ActivityService activityService;
    @Autowired
    private RedisService redisService;
    @Autowired
    private YxProductGroupBuyInfoService yxProductGroupBuyInfoService;
    @Autowired
    private DynamicService dynamicService;
    @Autowired
    private OrdersService ordersService;
    @Resource
    private ProductImgMapper productImgMapper;
    @Resource
    private OrdersInfoMapper ordersInfoMapper;
    @Resource
    private ProductMapper productMapper;
    @Resource
    private SupplyApiConfig supplyApiConfig;
    @Value("${fixRatio:10}")
    private String fixRatio;
    @Value("${gaode.key:8ee7f00ac447f13f6f098491e446d6b4}")
    private String gaodeKey;
    /**
     * 根据ip解析地址方式
     * gaode=高德
     * local=本地地址库
     */
    @Value("${ip.type:gaode}")
    private String ipType;
    /**
     * ipType=local 时的源文件存放路径
     */
    @Value("${ip.sourcefile.path:}")
    private String ipSourceFilePath;
    @Value("${order.region:吴江区}")
    private String regionAddress;

    @Autowired
    private FrontCategoryService frontCategoryService;
    @Resource
    private AdvertCallBackService advertCallBackService;

    @Value("${baiduToken:FnMsmoneZfIY1SS7AGekqFfYcq1LlIcu@I0rZjsLf9rRbosPGVorrB8ylDwBeFMFj}")
    private String baiduToken;

    public ProductController(ProductService productService, UsersClient usersClient) {
        this.productService = productService;
        this.usersClient = usersClient;
    }


    /**
     * 获取首页推荐商品列表
     *
     * @param request
     * @return
     */
    @PostMapping("/getProductList")
    public CommonResult getProductList(@RequestBody ProductListRequest request) {
        return CommonResult.success(productService.getProductList(request.getType(),
                Optional.ofNullable(request.getSpecialId()).orElse(null)
                , request.getPageNum(), request.getPageSize(), null));

    }

    /**
     * 获取首页推荐商品列表(new 根据专区找商品)
     *
     * @param request
     * @return
     */
    @PostMapping("/getProductListNew")
    public CommonResult getProductListNew(@RequestBody ProductListRequest request) {
        return CommonResult.success(productService.getProductListNew(request));
    }

    /**
     * 获取首页推荐商品列表(new 根据专区找商品)
     * @param request
     * @return
     */
    @PostMapping("/getProductListNewFixPrice")
    public CommonResult getProductListNewFixPrice(@RequestBody ProductListRequest request) {
            return CommonResult.success(productService.getProductListNewFixPrice(request));
    }

    /**
     * 获取专区推荐商品
     *
     * @param specialId
     * @return
     */
    @GetMapping("/getSpecialRecommendProduct")
    public CommonResult getSpecialRecommendProduct(@RequestParam("specialId") Integer specialId) {
        return CommonResult.success(productService.getSpecialRecommendProduct(specialId));
    }

    /**
     * 获取推荐商品列表
     * <p>
     * 大图
     *
     * @return
     */
    @GetMapping("/getRecommendProductList")
    public CommonResult getRecommendProductList(@RequestParam(value = "productId", required = false) Integer productId,
                                                @RequestParam(value = "pageNum") Integer pageNum,
                                                @RequestParam(value = "pageSize") Integer pageSize,
                                                @RequestParam(value = "activityType", required = false) String activityType) {
        UsersResponse usersResponse = getH5CurrentUser();
        List<HomeRecommendResponse> productResponseList = productService.getRecommendProductList(productId, pageNum, pageSize, usersResponse, activityType);
        return CommonResult.success(productResponseList);
    }


    /**
     * 获取活动列表
     *
     * @return
     */
    @GetMapping("/getActivityList")
    public CommonResult getActivityList(@RequestParam(value = "pageNum", required = false, defaultValue = "1") Integer pageNum,
                                        @RequestParam(value = "pageSize", required = false, defaultValue = "100") Integer pageSize,
                                        @RequestParam(value = "type", required = false, defaultValue = "COMPOSITE") String type) {
        UsersResponse usersResponse = getH5CurrentUser();
        return CommonResult.success(productService.getActivityList(usersResponse, pageNum, pageSize, type));
    }

    @Resource
    private CouponRecordsDao couponRecordsDao;

    @Resource
    private AdvertReportUtil advertReportUtil;

    @Resource
    private ProductRecordUtil productRecordUtil;

    @Resource
    private OrdersDao ordersDao;

    /**
     * 根据商品id获取商品信息
     * @param productId 商品ID
     * @param modular
     * @param scene 场景值
     * @return
     */
    @GetMapping("/getProductInfoById")
        public CommonResult getProductInfoById(@RequestParam("productId") Integer productId,
                                               @RequestParam(value = "pageSourceV2", required = false) String modular,
                                               @RequestParam(value = "scene", required = false) String scene) {

        log.debug("====getProductInfoById====时间1={}", System.currentTimeMillis());
        ProductResponse productResponse = new ProductResponse();
        String volumnStr = "0";
        Integer topCategoryId = 0;
        Integer categoryId = 0;
        Integer bottomCategoryId = 0;
        try {
            String source = getSource();
            if (DynamicConstant.SOURCE_H5.equals(source) || DynamicConstant.SOURCE_QA.equals(source)
                    || "quick-app".equals(source) || "app".equals(source) || "h5_2".equals(source) || "h5_3".equals(source)) {
                productResponse = productService.getProductById(productId, modular);
            } else {
                UsersResponse currentUser = getH5CurrentUser();
                if (currentUser == null) {
                    productResponse = productService.getProductById(productId, modular);
                } else {
                    productResponse = productService.getProductByIdV2(productId, currentUser.getId(), modular);
                }
            }
            //虚拟销量值
            volumnStr = productResponse.getVolumeStr();
            //一级分类id
            topCategoryId = productResponse.getTopCategoryId();
            //二级分类id
            categoryId = productResponse.getCategoryId();
            //三级分类id
            bottomCategoryId = productResponse.getBottomCategoryId();
            // 领取补贴价
            if ("OLD_FOR_NEW".equals(productResponse.getActivityType())) {
                if (DynamicConstant.SOURCE_H5.equals(source)) {
                    String token = TokenUtil.getToken();
                    String subsidyKey = RedisConstants.SUBSIDYKEY;
                    Map<Object, Object> subsidyHash = redisService.getHashEntries(subsidyKey + token);
                    Object subsidyData = subsidyHash.get(productId.toString());
                    if (null == subsidyData) {
                        productResponse.setIsReceiveSubsidy(0);
                    } else {
                        RecordSubsidyDataDto subsidyDto = this.getUserSubdidy(token, RedisConstants.RECORD_SUBSIDYKEY);
                        productResponse.setTotalReceive(subsidyDto != null && subsidyDto.getReceived() != null
                                ? subsidyDto.getReceived().setScale(0, BigDecimal.ROUND_HALF_UP)
                                : BigDecimal.ZERO);
                        productResponse.setIsReceiveSubsidy(1);
                    }
                } else {
                    String token = TokenUtil.getUuid();
                    String subsidyKey = RedisConstants.SUBSIDYKEY_APP;
                    Map<Object, Object> subsidyHash = redisService.getHashEntries(subsidyKey + token);
                    Object subsidyData = subsidyHash.get(productId.toString());
                    if (null == subsidyData) {
                        productResponse.setIsReceiveSubsidy(0);
                    } else {
                        RecordSubsidyDataDto recordSubsidyDataDto = this.getUserSubdidy(token, RedisConstants.RECORD_SUBSIDYKEY_APP);
                        productResponse.setTotalReceive(recordSubsidyDataDto.getReceived().setScale(0, BigDecimal.ROUND_HALF_UP));
                        productResponse.setIsReceiveSubsidy(1);
                    }
                }
            }
            boolean groupActivity = false;
            BigDecimal groupActivityPrice = BigDecimal.ZERO;


            // 自动领取优惠券
            if ("CASH_COUPON".equals(productResponse.getActivityType())) {
                String token;
                if ("h5".equals(source)) {
                    token = TokenUtil.getToken();
                } else {
                    token = TokenUtil.getUuid();
                }
                CouponRecords couponRecords = couponRecordsDao.queryOne(productId, token, new Date(), source);
                if (couponRecords == null) {
                    // 没有领取
                    couponRecords = activityService.obtainCoupon(productId);
                    productResponse.setOverdueTime(couponRecords.getOverdueTime());
                } else {
                    // 领取
                    productResponse.setOverdueTime(couponRecords.getOverdueTime());
                }
                ReturnCouponResponse returnCouponResponse = this.getReturnCoupon();
                productResponse.setUserActivityMax(returnCouponResponse.getActivityMax());
            }
            boolean finalGroupActivity = groupActivity;
            BigDecimal finalGroupActivityPrice = groupActivityPrice;
            List<ProductSpecResponse> productSpecList = productService.getProductSpecList(productId);
            productResponse.setSpecMap(productSpecList.stream()
                    .collect(Collectors.toMap(item -> {
                        if (finalGroupActivity) {
                            item.setPrice(finalGroupActivityPrice);
                        }
                        String skuSpec = item.getSkuSpec();
                        String[] specList = skuSpec.split(",");
                        StringBuilder stringBuilder = new StringBuilder();
                        for (int i = 0; i < specList.length; i++) {
                            String key = specList[i].split(":")[1];
                            if (i == specList.length - 1) {
                                stringBuilder.append(key);
                            } else {
                                stringBuilder.append(key).append("-");
                            }
                        }
                        return stringBuilder.toString();
                }, item -> item)));

            Map<String, ProductSpecResponse> map = productResponse.getSpecMap();
            Collection<ProductSpecResponse> values = map.values();
            Iterator<ProductSpecResponse> iterator = values.iterator();
            Integer stock = 0;
            while (iterator.hasNext()) {
                stock = stock + iterator.next().getStock();
            }
            productResponse.setStock(stock);
            BigDecimal price = productSpecList.stream().filter(item -> item.getStock() != null && item.getStock() > 0).min(Comparator.comparing(ProductSpecResponse::getPrice)).get().getPrice();
            BigDecimal curPrice = productSpecList.stream().filter(item -> item.getStock() != null && item.getStock() > 0).min(Comparator.comparing(ProductSpecResponse::getCurPrice)).get().getCurPrice();
            BigDecimal originalPrice = productSpecList.stream().filter(item -> item.getStock() != null && item.getStock() > 0).min(Comparator.comparing(ProductSpecResponse::getOriginalPrice)).get().getOriginalPrice();

            productResponse.setPrice(Optional.ofNullable(price).orElse(productResponse.getPrice()));
            productResponse.setCurPrice(Optional.ofNullable(curPrice).orElse(productResponse.getCurPrice()));
            productResponse.setOriginalPrice(Optional.ofNullable(originalPrice).orElse(productResponse.getOriginalPrice()));

            // 商品统计
            ProductStatisticsRequest productStatisticsRequest = new ProductStatisticsRequest();
            productStatisticsRequest.setProductId(productResponse.getId());
            productStatisticsRequest.setActivityType(productResponse.getActivityType());
            productStatisticsRequest.setBankerId(productResponse.getBankerId());
            productStatisticsRequest.setIsActivity(productResponse.getProductType());
            productStatisticsRequest.setProductName(productResponse.getProductName());
            productStatisticsRequest.setScene(scene);
            //推广账号
            String childId = super.getChildId();
            if (StringUtils.isNotBlank(childId)){
                productStatisticsRequest.setAccount("");
            }else {
                productStatisticsRequest.setAccount("");
            }
            productRecordUtil.browsingHistory(productStatisticsRequest);
        } catch (Exception e) {
            log.info("===getProductInfoById==={}", e);
            return CommonResult.success(productResponse);
        }

        if (null == productResponse.getStock()) {
            productResponse.setStock(0);
        }

        productResponse.setDisableFlag(false);
//        try {
//            boolean addressCheckResult = checkAddress(productId);
//            productResponse.setDisableFlag(addressCheckResult);
//        } catch (Exception e) {
//            log.error("===判断偏远地区异常==={}", e);
//        }
        if (StringUtils.isBlank(productResponse.getShrinkImg())){
            productResponse.setShrinkImg(productResponse.getProductImg());
        }
        productResponse.setVolume(productResponse.getCommentSum());
        try {
            // 获得总榜排行
            String totalKey = "product:volumeStr:rank:total:" + productResponse.getId();
            String categoryKey = "product:volumeStr:rank:category:" + productResponse.getId();
            String totalRankVal = redisService.get(totalKey);
            String categoryRankVal = redisService.get(categoryKey);
            if (StringUtils.isNotEmpty(totalRankVal)) {
                productResponse.setTotalRank(Long.valueOf(totalRankVal));
            }else {
                long rank = productService.queryTotalRank(null, volumnStr,getSource());
                productResponse.setTotalRank(rank);
                redisService.set(totalKey, String.valueOf(rank));
                redisService.expire(totalKey, 5 * 60);
            }
            // 获得分类榜排行
            if (StringUtils.isNotEmpty(categoryRankVal)) {
                productResponse.setCategoryRank(Long.valueOf(categoryRankVal));
            }else {
                long rank = productService.queryTotalRank(topCategoryId, volumnStr,getSource());
                productResponse.setCategoryRank(rank);
                redisService.set(categoryKey, String.valueOf(rank));
                redisService.expire(categoryKey, 5 * 60);
            }
        } catch (Exception e) {}

        //推送百度事件信息
        try{
            String h5Token = TokenUtil.getToken();
            new Thread(()->{
                String usesInfo = redisService.get(h5Token);
                String a_oId = "";
                if (StringUtils.isNotBlank(usesInfo)) {
                    UsersResponse usersResponse = com.alibaba.fastjson.JSONObject.parseObject(usesInfo, UsersResponse.class);
                    if (StringUtils.isNotBlank(usersResponse.getAoId())) {
                        a_oId =  usersResponse.getAoId();
                    }
                }
                if(StringUtils.isNotBlank(a_oId)){
                    List<ConversionType> conversionTypes = new ArrayList<>();
                    // 编辑一条转化数据
                    ConversionType cv = new ConversionType();
                    cv.setLogidUrl(a_oId); // 设置落地页url
                    cv.setNewType(48); // 设置转化类型
                    cv.setConvertTime(System.currentTimeMillis() / 1000);
                    conversionTypes.add(cv);
                    BaiduApiUtil.sendConvertData(baiduToken, conversionTypes);
                }
            }).start();
        }catch (Exception e) {
            log.error("推送到百度事件信息错误:{}",e.getMessage());
        }



        return CommonResult.success(productResponse);
    }

    private boolean checkAddress(Integer productId) {
        String ip = IPUtil.getIpAddress(TokenUtil.getRequest());
        log.info("===checkAddress ip:{}, productId:{}===", ip, productId);
        String city = "";
        String area = "";
        try {
            log.debug("===ipType==={}", ipType);
            if ("gaode".equals(ipType)) {
                //高德方式
                AddressRequest request = resloveAddressByIp(ip);
                city = request.getCity();
                area = request.getArea();
            } else if ("local".equals(ipType)) {
                //地址库方式
                if (StringUtils.isEmpty(ipSourceFilePath)) {
                    ipSourceFilePath = "/mnt/ipsourcefile/qqzeng-ip-utf8.dat";
                }
                IpSearch finder = IpSearch.getInstance(ipSourceFilePath);
                String addressResult = finder.Get(ip);
                Map<String, String> hashMap = IpSearch.analysisResult(addressResult);
                city = hashMap.get("city");
                area = hashMap.get("area");
            }

        } catch (Exception e) {
            log.info("===解析ip对应城市失败==={}", ip);
            log.error("===解析ip对应城市失败ip:{}==={}", ip, e);
        }
//        log.info("===ip to city==={}, area==={}, {}", city, area,ipType);
        if (StringUtils.isEmpty(city)) {
            return false;
        }
        //获取运费模板
        FreightTemplateResponse freightTemplateResponse = ordersService.getFreightTemplateResponse(productId);
        if (null == freightTemplateResponse) {
            log.info("===商品：{}，运费模板不存在");
            return false;
        }
        //判断是否在限制地区
        YxAstrictRegionResponse astrictRegion = freightTemplateResponse.getAstrictRegion();
        if (null != astrictRegion && StringUtils.isNotBlank(astrictRegion.getRegion())){
            String[] region = astrictRegion.getRegion().split(",");
//            region = ArrayUtil.add(region, regionAddress);
            String finalCity = city;
            String finalArea = area;
            Optional<String> regionFlag = Stream.of(region).filter(x -> x.equals(finalCity)).findFirst();
            Optional<String> finalAreaFlag = Stream.of(region).filter(x -> x.equals(finalArea)).findFirst();
            if ((regionFlag.isPresent() && StringUtils.isNotBlank(regionFlag.get()))
                    || (finalAreaFlag.isPresent() && StringUtils.isNotBlank(finalAreaFlag.get()))) {
                return true;
            }


        }
        return false;
    }

    /**
     * 根据ip解析地址信息
     * @param ip
     * @return
     */
    private AddressRequest resloveAddressByIp(String ip) {
        AddressRequest addressRequest = new AddressRequest();
        try {
            String ipAddressStrVal = redisService.getMapString("ip:address", ip);
            if (!StringUtils.isEmpty(ipAddressStrVal)) {
                addressRequest = com.alibaba.fastjson.JSONObject.parseObject(ipAddressStrVal, AddressRequest.class);
                if (null != addressRequest) {
                    return addressRequest;
                }
            }
        } catch (Exception e) {

        }

//        String addressByIp = AliyunOSSClientUtil.getAddressByIp(ip);
        String addressByIp = IPUtil.getGaodeAddressByIdVersionOne(gaodeKey, ip);
        if(StringUtil.isEmpty(addressByIp)){
            return addressRequest;
        }
        HashMap hashMap = com.alibaba.fastjson.JSONObject.parseObject(addressByIp, HashMap.class);
        if (!"1".equals(hashMap.get("status"))) {
            return addressRequest;
        }
        if (!"OK".equals(hashMap.get("info"))) {
            return addressRequest;
        }
        log.info("gaode addressInfo:{}",com.alibaba.fastjson.JSONObject.toJSON(hashMap));
        String province = hashMap.get("province").toString();
        String city = hashMap.get("city").toString();
        String area = hashMap.getOrDefault("county","").toString();
//        String area = "";
        if(province.contains("重庆")){
            addressRequest.setProvince("重庆市");
            addressRequest.setCity("市辖区");
            addressRequest.setArea("万州区");
            return addressRequest;
        }
        if(province.contains("北京")){
            addressRequest.setProvince("北京市");
            addressRequest.setCity("市辖区");
            addressRequest.setArea("东城区");
            return addressRequest;
        }
        if(province.contains("天津")){
            addressRequest.setProvince("天津市");
            addressRequest.setCity("市辖区");
            addressRequest.setArea("和平区");
            return addressRequest;
        }
        if(province.contains("上海")){
            addressRequest.setProvince("上海市");
            addressRequest.setCity("市辖区");
            addressRequest.setArea("黄埔区");
            return addressRequest;
        }
        if(province.contains("台湾")){
            addressRequest.setProvince("台湾");
            addressRequest.setCity("台北");
            addressRequest.setArea("台北");
            return addressRequest;
        }
        if(province.contains("香港")){
            addressRequest.setProvince("香港");
            addressRequest.setCity("香港岛");
            addressRequest.setArea("香港岛");
            return addressRequest;
        }
        if(province.contains("澳门")){
            addressRequest.setProvince("澳门");
            addressRequest.setCity("澳门半岛");
            addressRequest.setArea("澳门半岛");
            return addressRequest;
        }
        if(province.contains("钓鱼")){
            addressRequest.setProvince("钓鱼岛");
            addressRequest.setCity("钓鱼岛");
            addressRequest.setArea("钓鱼岛全岛");
            return addressRequest;
        }
        addressRequest.setProvince(province);
        addressRequest.setCity(city);
        addressRequest.setArea(area);
        try {
            redisService.add("ip:address", ip, com.alibaba.fastjson.JSONObject.toJSONString(addressRequest));
        } catch (Exception e) {}

        return addressRequest;
    }

    /**
     * 根据商品id获取商品信息
     *
     * @param productId
     * @return
     */
    @GetMapping("/obtainSubsidy")
    public CommonResult obtainSubsidy(@RequestParam("productId") Integer productId,
                                           @RequestParam(value = "pageSourceV2", required = false) String modular) {
        ProductResponse productResponse;
        if (DynamicConstant.SOURCE_H5.equals(getSource()) || DynamicConstant.SOURCE_QA.equals(getSource())) {
            productResponse = productService.getProductById(productId, modular);
        } else {
            UsersResponse currentUser = getH5CurrentUser();
            if (currentUser == null) {
                productResponse = productService.getProductById(productId, modular);
            } else {
                productResponse = productService.getProductByIdV2(productId, currentUser.getId(), modular);
            }
        }
        // 领取补贴价
        if ("OLD_FOR_NEW".equals(productResponse.getActivityType())) {
            if (DynamicConstant.SOURCE_H5.equals(getSource())|| DynamicConstant.SOURCE_QA.equals(getSource())) {
                String token = TokenUtil.getToken();
                String subsidyKey = RedisConstants.SUBSIDYKEY;
                Map<Object, Object> subsidyHash = redisService.getHashEntries(subsidyKey + token);
                Object subsidyData = subsidyHash.get(productId.toString());
                if (null == subsidyData) {
                    SubsidyDataDto subsidyDataDto = new SubsidyDataDto();
                    subsidyDataDto.setToken(token);
                    subsidyDataDto.setProductId(productId);
                    subsidyDataDto.setActivityMax(productResponse.getActivityMax());
                    subsidyDataDto.setReceiveTime(new Date());
                    redisService.add(subsidyKey + token, productId.toString(), JSON.toJSONString(subsidyDataDto));
                    redisService.expire(subsidyKey + token, ExpireTimeConstant.SUBSIDY_DATA_TIME);
                    // 增加领取的补贴
                    RecordSubsidyDataDto recordSubsidyDataDto = this.addReceivedSubsidy(productResponse.getActivityMax(), RedisConstants.RECORD_SUBSIDYKEY, token);

                    productResponse.setTotalReceive(recordSubsidyDataDto.getReceived().setScale(0, BigDecimal.ROUND_HALF_UP));
                    productResponse.setIsReceiveSubsidy(0);
                } else {
                    RecordSubsidyDataDto subsidyDto = this.getUserSubdidy(token, RedisConstants.RECORD_SUBSIDYKEY);
                    productResponse.setTotalReceive(subsidyDto != null && subsidyDto.getReceived() != null
                            ? subsidyDto.getReceived().setScale(0, BigDecimal.ROUND_HALF_UP)
                            : BigDecimal.ZERO);
                    productResponse.setIsReceiveSubsidy(1);
                }
            } else {
                String token = TokenUtil.getUuid();
                String subsidyKey = RedisConstants.SUBSIDYKEY_APP;
                Map<Object, Object> subsidyHash = redisService.getHashEntries(subsidyKey + token);
                Object subsidyData = subsidyHash.get(productId.toString());
                if (null == subsidyData) {
                    SubsidyDataDto subsidyDataDto = new SubsidyDataDto();
                    subsidyDataDto.setToken(token);
                    subsidyDataDto.setProductId(productId);
                    subsidyDataDto.setActivityMax(productResponse.getActivityMax());
                    subsidyDataDto.setReceiveTime(new Date());
                    redisService.add(subsidyKey + token, productId.toString(), JSON.toJSONString(subsidyDataDto));
                    redisService.expire(subsidyKey + token, ExpireTimeConstant.SUBSIDY_DATA_TIME);
                    // 增加领取的补贴
                    RecordSubsidyDataDto recordSubsidyDataDto = this.addReceivedSubsidy(productResponse.getActivityMax(), RedisConstants.RECORD_SUBSIDYKEY_APP, token);

                    productResponse.setTotalReceive(recordSubsidyDataDto.getReceived().setScale(0, BigDecimal.ROUND_HALF_UP));
                    productResponse.setIsReceiveSubsidy(0);
                } else {
                    RecordSubsidyDataDto recordSubsidyDataDto = this.getUserSubdidy(token, RedisConstants.RECORD_SUBSIDYKEY_APP);
                    productResponse.setTotalReceive(recordSubsidyDataDto.getReceived().setScale(0, BigDecimal.ROUND_HALF_UP));
                    productResponse.setIsReceiveSubsidy(1);
                }
            }
        }

        return CommonResult.success();
    }


    /**
     * 获取商品详情页中的品牌推荐
     *
     * @return
     */
    @GetMapping("/getBrandPdInProductDetails")
    public CommonResult getBrandPdInProductDetails(@RequestParam("productId") Integer productId) {
        return CommonResult.success(productService.getBrandPdInProductDetails(productId));
    }

    /**
     * 查询0元试用列表
     * @return
     */
    @GetMapping("/getSelectExclusive")
    public CommonResult getSelectExclusive(Integer pageNum,Integer pageSize,Integer type) {
        //UsersResponse currentUser = getCurrentUser();
        return CommonResult.success(productService.selectExclusive(pageNum,pageSize,type));
    }

    /**
     * 我的
     * 查询0元试用·专属商品列表
     * @return
     */
    @GetMapping("/getMyExclusive")
    public CommonResult getMyExclusive(Integer pageNum,Integer pageSize,Integer type) {
       UsersResponse currentUser = getCurrentUser();
        return CommonResult.success(productService.MyExclusive(pageNum,pageSize,type,currentUser.getId()));
    }

    /**
     * 我的
     * 查询0元试用·专属商品详情
     * @return
     */
    @GetMapping("/getMyExclusiveId")
    public CommonResult getMyExclusiveId(Integer id) {
        return CommonResult.success(productService.MyExclusiveId(id));
    }

    /**
     * 获取商品详情页中的品牌推荐 固定飞克id
     *
     * @return
     */
    @GetMapping("/getFeikePdInProductDetails")
    public CommonResult getFeikePdInProductDetails() {
        return CommonResult.success(productService.getFeikePdInProductDetails());
    }

    private ReturnCouponResponse getReturnCoupon() {
        ReturnCouponResponse returnCouponResponse = new ReturnCouponResponse();
        String key;

        if ("h5".equals(TokenUtil.getSource())) {
            key = RedisConstants.RETURN_COUPON + TokenUtil.getToken();
        }else {
            key = RedisConstants.RETURN_COUPON_APP + TokenUtil.getUuid();
        }
        String cs = redisService.get(key);
        if (StringUtils.isNotEmpty(cs)) {// 记录用户返现红包金额
            returnCouponResponse = com.alibaba.fastjson.JSONObject.parseObject(cs, ReturnCouponResponse.class);
        }

        returnCouponResponse.setUsedActivityMax(Optional.ofNullable(returnCouponResponse.getUsedActivityMax())
                .orElse(BigDecimal.ZERO).setScale(0, BigDecimal.ROUND_HALF_UP));
        returnCouponResponse.setTotalReturnCoupon(Optional.ofNullable(returnCouponResponse.getTotalReturnCoupon())
                .orElse(BigDecimal.ZERO).setScale(0, BigDecimal.ROUND_HALF_UP));
        returnCouponResponse.setActivityMax(Optional.ofNullable(returnCouponResponse.getActivityMax())
                .orElse(new BigDecimal(680)).setScale(0, BigDecimal.ROUND_HALF_UP));

        return returnCouponResponse;
    }

    private RecordSubsidyDataDto getUserSubdidy(String token, String recordSubsidykeyApp) {
        RecordSubsidyDataDto recordSubsidyDataDto = new RecordSubsidyDataDto();

        String recordKey = recordSubsidykeyApp + token;
        String recordSubsidyData = redisService.get(recordKey);
        if (StringUtils.isNotEmpty(recordSubsidyData)) {
            recordSubsidyDataDto = com.alibaba.fastjson.JSONObject.parseObject(recordSubsidyData, RecordSubsidyDataDto.class);
        }

        recordSubsidyDataDto.setUsed(Optional.ofNullable(recordSubsidyDataDto.getUsed()).orElse(BigDecimal.ZERO));
        recordSubsidyDataDto.setReceived(Optional.ofNullable(recordSubsidyDataDto.getReceived()).orElse(BigDecimal.ZERO));
        recordSubsidyDataDto.setToken(Optional.ofNullable(recordSubsidyDataDto.getToken()).orElse(token));
        recordSubsidyDataDto.setReceiveTime(Optional.ofNullable(recordSubsidyDataDto.getReceiveTime()).orElse(new Date()));

        return recordSubsidyDataDto;

    }



    private RecordSubsidyDataDto addReceivedSubsidy(BigDecimal productActivityMax, String recordKeyHead, String token) {
        RecordSubsidyDataDto recordSubsidyDataDto = new RecordSubsidyDataDto();

        String recordKey = recordKeyHead + token;
        String recordSubsidyData = redisService.get(recordKey);
        if (StringUtils.isNotEmpty(recordSubsidyData)) {
            recordSubsidyDataDto = com.alibaba.fastjson.JSONObject.parseObject(recordSubsidyData, RecordSubsidyDataDto.class);
        }

        // 已领取补贴
        BigDecimal receivedSubsidy = Optional.ofNullable(recordSubsidyDataDto.getReceived())
                .orElse(BigDecimal.ZERO)
                .setScale(2, BigDecimal.ROUND_HALF_UP);
        // 商品补贴 + 已领取补贴
        receivedSubsidy = receivedSubsidy
                .add(productActivityMax).setScale(2, BigDecimal.ROUND_HALF_UP);

        recordSubsidyDataDto.setReceived(receivedSubsidy);
        recordSubsidyDataDto.setToken(Optional.ofNullable(recordSubsidyDataDto.getToken()).orElse(token));
        recordSubsidyDataDto.setReceiveTime(Optional.ofNullable(recordSubsidyDataDto.getReceiveTime()).orElse(new Date()));
        recordSubsidyDataDto.setUsed(Optional.ofNullable(recordSubsidyDataDto.getUsed()).orElse(BigDecimal.ZERO).setScale(2, BigDecimal.ROUND_HALF_UP));

        redisService.set(recordKey, JSON.toJSONString(recordSubsidyDataDto));
        redisService.expire(recordKey, ExpireTimeConstant.SUBSIDY_DATA_TIME);
        return recordSubsidyDataDto;
    }


    /**
     * 根据商品id获取商品信息(h5推广)
     *
     * @param productId
     * @return
     */
    @GetMapping("/queryProductInfo")
    public CommonResult queryProductInfo(@RequestParam("productId") Integer productId) {
        ProductExtResponse productResponse = productService.queryProductExtInfo(productId);
        ;
        UsersResponse currentUser = getH5CurrentUser();
        // 是否收藏
        if (currentUser == null) {
            productResponse.setIsCollect(IsCollectConstant.NO);
        } else {
            if (!DynamicConstant.SOURCE_H5.equals(getSource())
                    && !DynamicConstant.SOURCE_QA.equals(getSource())) {
                productResponse.setIsCollect(
                        Optional.ofNullable(usersClient.isCollect(productResponse.getId(), currentUser.getId())).orElse(0));
            }
        }
        // 自动领取优惠券
        if ("CASH_COUPON".equals(productResponse.getActivityType())) {
            String token;
            String source = TokenUtil.getSource();
            if ("h5".equals(source)) {
                token = TokenUtil.getToken();
            } else {
                token = TokenUtil.getUuid();
            }
            CouponRecords couponRecords = couponRecordsDao.queryOne(productId, token, new Date(), source);
            if (couponRecords == null) {
                // 没有领取
                couponRecords = activityService.obtainCoupon(productId);
                productResponse.setOverdueTime(couponRecords.getOverdueTime());
            } else {
                // 领取
                productResponse.setOverdueTime(couponRecords.getOverdueTime());
            }
        }
        // 商品统计
        ProductStatisticsRequest productStatisticsRequest = new ProductStatisticsRequest();
        productStatisticsRequest.setProductId(productResponse.getId());
        productStatisticsRequest.setActivityType(productResponse.getActivityType());
        productStatisticsRequest.setBankerId(productResponse.getBankerId());
        productStatisticsRequest.setIsActivity(productResponse.getProductType());
        productStatisticsRequest.setProductName(productResponse.getProductName());
        productRecordUtil.browsingHistory(productStatisticsRequest);

        productResponse.setSpecMap(productService.getProductSpecList(productId).stream()
                .collect(Collectors.toMap(item -> {
                    String skuSpec = item.getSkuSpec();
                    String[] specList = skuSpec.split(",");
                    StringBuilder stringBuilder = new StringBuilder();
                    for (int i = 0; i < specList.length; i++) {
                        String key = specList[i].split(":")[1];
                        if (i == specList.length - 1) {
                            stringBuilder.append(key);
                        } else {
                            stringBuilder.append(key).append("-");
                        }
                    }
                    return stringBuilder.toString();
                }, item -> item)));
        String token = TokenUtil.getToken();
        String subsidyKey = RedisConstants.SUBSIDYKEY;
        if (ActivityTypeEnums.OLD_FOR_NEW.name().equals(productResponse.getActivityType())) {
            Map<Object, Object> subsidyHash = redisService.getHashEntries(subsidyKey + token);
            Object subsidyData = subsidyHash.get(productId.toString());
            if (null == subsidyData) {
                SubsidyDataDto subsidyDataDto = new SubsidyDataDto();
                subsidyDataDto.setToken(token);
                subsidyDataDto.setProductId(productId);
                subsidyDataDto.setActivityMax(productResponse.getActivityMax());
                subsidyDataDto.setReceiveTime(new Date());
                redisService.add(subsidyKey + token, productId.toString(), JSON.toJSONString(subsidyDataDto));
                redisService.expire(subsidyKey + token, ExpireTimeConstant.SUBSIDY_DATA_TIME);
                // 增加领取的补贴
                RecordSubsidyDataDto recordSubsidyDataDto = this.addReceivedSubsidy(productResponse.getActivityMax(), RedisConstants.RECORD_SUBSIDYKEY, token);

                productResponse.setTotalReceive(recordSubsidyDataDto.getReceived());
                productResponse.setIsReceiveSubsidy(0);
            } else {
                RecordSubsidyDataDto recordSubsidyDataDto = this.getUserSubdidy(token, RedisConstants.RECORD_SUBSIDYKEY);
                productResponse.setTotalReceive(recordSubsidyDataDto != null && recordSubsidyDataDto.getReceived() != null ? recordSubsidyDataDto.getReceived() : BigDecimal.ZERO);
                productResponse.setIsReceiveSubsidy(1);
            }
        }
        return CommonResult.success(productResponse);
    }

    /**
     * 获取商品相关推荐
     *
     * @param specialId
     * @return
     */
    @GetMapping("/getCorrelationProduct")
    public CommonResult getCorrelationProduct(@RequestParam(value = "specialId", required = false) Integer specialId,
                                              @RequestParam("productId") Integer productId) {
        return CommonResult.success(productService.getCorrelationProduct(specialId, productId));
    }

    /**
     * 获取商品规格信息
     *
     * @param productSpecRequest
     * @return
     */
    @PostMapping("/getProductSpecInfo")
    public CommonResult getProductSpecInfo(@RequestBody ProductSpecRequest productSpecRequest) {
        return CommonResult.success(productService.getProductSpecInfo(productSpecRequest.getProductId(), productSpecRequest.getProductSpec()));
    }

    @Autowired
    private ElasticsearchTemplate template;

    /**
     * 搜索商品
     *
     * @param name
     * @return
     */
    @GetMapping("/searchProducts")
    public CommonResult searchProducts(@RequestParam("name") String name) {
        BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder()
                .must(multiMatchQuery(name, "product_name", "descr"))
                .must(termQuery("status", ProductStatusEnums.UP.getValue()));
        Pageable pageable = PageRequest.of(0, 100);
        SearchQuery searchQuery = new NativeSearchQueryBuilder()
                .withQuery(boolQueryBuilder)
                .withPageable(pageable)
                .build();
        List<ProductEsDto> list = template.queryForList(searchQuery, ProductEsDto.class);
        return CommonResult.success(list);
    }

    @Autowired
    private SysConfigUtil sysConfigUtil;

    @GetMapping("/searchProductsV2")
    public CommonResult searchProductsV2(@RequestParam("name") String name,
                                         @RequestParam("type") String type) {


        Integer searchNum = Integer.valueOf(sysConfigUtil.getSysConfig(SysConfigConstants.SEARCH_NUM));
        BoolQueryBuilder activityBoolQueryBuilder = new BoolQueryBuilder()
                .must(multiMatchQuery(name, "product_name", "descr"))
                .must(termQuery("status", ProductStatusEnums.UP.getValue()));
        Pageable pageable = PageRequest.of(0, searchNum);
        SearchQuery activitySearchQuery = new NativeSearchQueryBuilder()
                .withQuery(activityBoolQueryBuilder)
                .withPageable(pageable)
                .build();
        List<ProductActivityEsDto> productActivityEsDtoList = template.queryForList(activitySearchQuery, ProductActivityEsDto.class);
        List<SearchProductResponse> searchProductResponseList = productActivityEsDtoList.stream().filter(item -> {
            if (ActivityTypeEnums.SECKILL.name().equals(item.getActivityType())) {
                if (item.getColumnId().intValue() == 4) {
                    return true;
                } else {
                    return false;
                }
            } else {
                return true;
            }
        }).map(SearchProductResponse::new).collect(Collectors.toList());


        if (searchProductResponseList.size() < searchNum) {
            BoolQueryBuilder productBoolQueryBuilder = new BoolQueryBuilder()
                    .must(multiMatchQuery(name, "product_name", "descr"))
                    .must(termQuery("status", ProductStatusEnums.UP.getValue()));
            pageable = PageRequest.of(0, searchNum - productActivityEsDtoList.size());
            SearchQuery searchQuery = new NativeSearchQueryBuilder()
                    .withQuery(productBoolQueryBuilder)
                    .withPageable(pageable)
                    .build();
            List<ProductEsDto> productEsDtoList = template.queryForList(searchQuery, ProductEsDto.class);
            List<SearchProductResponse> searchProductResponses = productEsDtoList.stream().map(SearchProductResponse::new).collect(Collectors.toList());
            searchProductResponseList.addAll(searchProductResponses);
        }
        if ("COMPOSITE".equals(type)) {
        }
        if ("VOLUME".equals(type)) {
            searchProductResponseList = searchProductResponseList.stream().sorted(Comparator.comparing(SearchProductResponse::getVolume).reversed()).collect(Collectors.toList());
        }
        if ("PRICE_MAX".equals(type)) {
            searchProductResponseList = searchProductResponseList.stream().sorted(Comparator.comparing(SearchProductResponse::getPrice).reversed()).collect(Collectors.toList());
        }
        if ("PRICE_MIN".equals(type)) {
            searchProductResponseList = searchProductResponseList.stream().sorted(Comparator.comparing(SearchProductResponse::getPrice)).collect(Collectors.toList());
        }
        return CommonResult.success(searchProductResponseList);
    }

    /**
     * 热词列表
     *
     * @return
     */
    @GetMapping("/hotSearch")
    public CommonResult hotSearch() {
        List<Object> list = redisService.range(RedisConstants.HOT_SEARCH, 0, -1);
        return CommonResult.success(list.stream()
                .map(JSONObject::new)
                .filter(item -> item.getStr("type").equals("HOME"))
                .sorted(Comparator.comparing(item -> item.getInt("sort")))
                .collect(Collectors.toList()));
    }


    /**
     * @Description 获取es推荐商品列表
     *
     *
     * @Version 1.0
     **/
    @GetMapping("/getEsRecommendProductList")
    public CommonResult getRecommendProductList(@RequestParam(value = "productId", required = false) Integer productId,
                                                @RequestParam(value = "name", required = false) String name,
                                                @RequestParam("type") String type,
                                                @RequestParam(value = "activityType", required = false) String activityType) {
        List<SearchProductResponse> esRecommendProductList = null;
        if (productId != null) {
            UsersResponse currentUser = this.getCurrentUser();
            esRecommendProductList = productService.getEsRecommendProductList(productId, currentUser, type, name, activityType);
        } else {
            UsersResponse currentUser = this.getH5CurrentUser();
            esRecommendProductList = productService.getEsRecommendProductList(productId, currentUser, type, name, activityType);
        }
        return CommonResult.success(esRecommendProductList);
    }

    /**
     * 猜你喜欢商品
     * @param productId
     * @param limit
     * @param activityType
     * @return
     */
    @GetMapping("/guessLike")
    public CommonResult getGuessLikeProduct(@RequestParam(value = "productId", required = false) Integer productId,
                                            @RequestParam(value = "limit", required = false) Integer limit,
                                            @RequestParam(value = "activityType", required = false) String activityType) {
        List<Product> esRecommendProductList = null;
        if (StringUtils.isNotEmpty(activityType)) {
            esRecommendProductList = productService.queryGuessLikeByActivity(1, limit, productId, activityType);
        } else {
            esRecommendProductList = productService.queryGuessLikeByNormal(1, limit, productId);
        }
        return CommonResult.success(esRecommendProductList);
    }

    /**
     * 猜你喜欢商品
     * @param productId
     * @param limit
     * @param activityType
     * @return
     */
    @GetMapping("/guessLikeOrDynamicProduct")
    public CommonResult guessLikeOrDynamicProduct(@RequestParam(value = "productId", required = false) Integer productId,
                                            @RequestParam(value = "limit", required = false) Integer limit,
                                            @RequestParam(value = "activityType", required = false) String activityType) {
        List<Product> esRecommendProductList = null;
        UsersResponse currentUser = null;
        UsersResponse usersResponse = null;
        Integer isQuality = null;
        Integer talentFlag = null;
        try {
            currentUser = this.getH5CurrentUser();
            Integer count = dynamicService.getDynamicCountByUserId(currentUser.getId(), DynamicStatusEnums.PASS.getCode());
            if (null != count && count > 0) {
                isQuality = 1;
                talentFlag = 1;
            }else {
                count = dynamicService.getDynamicCountByUserId(currentUser.getId(), null);
                if (null != count && count > 0) {
                    isQuality = 1;
                }
            }
            log.info("===isQuality={}, talentFlag={}", isQuality, talentFlag);
        } catch (Exception e) {
            log.error("===用户未登录==={}", e);
        }
        if (null != isQuality && null != talentFlag && (isQuality.equals(1) || talentFlag.equals(1))) {
            List<Dynamic> dynamicList = dynamicService.getDynamicIdsByUserId(currentUser.getId());
            List<ProductDto> result = new LinkedList<>();
            if (!CollectionUtils.isEmpty(dynamicList)) {
                dynamicList.stream().forEach(item -> {
                    ProductDto dto = new ProductDto();
                    dto.setProductName(item.getProductName());
                    dto.setId(item.getProductId());
                    ProductImgExample example = new ProductImgExample();
                    example.setOrderByClause("sort asc");
                    example.createCriteria()
                            .andProductIdEqualTo(item.getProductId());
                    List<ProductImg> imgs = productImgMapper.selectByExample(example);
                    dto.setImgs(imgs.stream().filter(img -> "banner".equals(img.getType())).map(img -> img.getImgUrl()).limit(3).collect(Collectors.toList()));

                    BigDecimal productPrice = item.getProdcutPrice(); //商品售价
                    BigDecimal brokerage = productPrice.multiply(new BigDecimal(fixRatio)).setScale(4, RoundingMode.HALF_UP).divide(new BigDecimal("100"), 2, RoundingMode.HALF_UP);
                    dto.setIncomeAmount(brokerage);
                    dto.setDynamicId(item.getId());
                    dto.setDynamicType(item.getDynamicType());
                    result.add(dto);
                });
            }
            return CommonResult.success(result);
        }
        if (StringUtils.isNotEmpty(activityType)) {
            esRecommendProductList = productService.queryGuessLikeByActivity(1, limit, productId, activityType);
        } else {
            esRecommendProductList = productService.queryGuessLikeByNormal(1, limit, productId);
        }
        return CommonResult.success(esRecommendProductList);
    }

    /**
     * @Description 获取es推荐《包含下架》商品列表
     *
     *
     * @Version 1.0
     **/
    @GetMapping("/getEsRecommendProductListDown")
    public CommonResult getEsRecommendProductListDown(@RequestParam(value = "productId", required = false) Integer productId,
                                                      @RequestParam(value = "name", required = false) String name,
                                                      @RequestParam("type") String type,
                                                      @RequestParam(value = "activityType", required = false) String activityType) {
        List<SearchProductResponse> esRecommendProductList = null;
        if (productId != null) {
            UsersResponse currentUser = this.getCurrentUser();
            esRecommendProductList = productService.getEsRecommendProductListDown(productId, currentUser, type, name, activityType);
        } else {
            UsersResponse currentUser = this.getH5CurrentUser();
            esRecommendProductList = productService.getEsRecommendProductListDown(productId, currentUser, type, name, activityType);
        }
        return CommonResult.success(esRecommendProductList);
    }

    /**
     * 钱包热门推荐
     *
     * @return
     */
    @GetMapping("/getHotRecommend")
    public CommonResult getHotRecommend(@RequestParam(value = "pageNum", required = false, defaultValue = "1") Integer pageNum,
                                        @RequestParam(value = "pageSize", required = false, defaultValue = "100") Integer pageSize,
                                        @RequestParam(value = "type", required = false, defaultValue = "COMPOSITE") String type) {
        UsersResponse currentUser = this.getH5CurrentUser();
        List<SearchProductResponse> searchProductResponseList = productService.getHotRecommend(currentUser, pageNum, pageSize, type);
        return CommonResult.success(searchProductResponseList);
    }


    /**
     * @Description 画廊大图浏览记录
     *
     *
     * @Version 1.0
     **/
    @GetMapping("/recommendProductBroweRecord")
    public CommonResult recommendProductBroweRecord(@RequestParam("productId") Integer productId,
                                                    @RequestParam(value = "activityType", required = false) String activityType,
                                                    @RequestParam(value = "pageSourceV2", required = false) String pageSourceV2) {
        if (!"h5".equals(getSource())) {
            UsersResponse currentUser = this.getH5CurrentUser();
            if (currentUser == null) {
                productService.recordProductBrowe(productId, activityType, null, pageSourceV2);
            } else {
                productService.recordProductBrowe(productId, activityType, currentUser.getId(), pageSourceV2);
            }
        } else {
            productService.recordProductBrowe(productId, activityType, null, pageSourceV2);
        }
        return CommonResult.success(ResultCode.SUCCESS);
    }

    @GetMapping("/getProductReviews")
    public CommonResult getProductReviews(@RequestParam(value = "productId", required = false) Integer productId) {
        return CommonResult.success(productService.getProductReviews(productId));
    }

    /**
     * 用户的购买记录 fake
     *
     * @param productId
     * @return
     */
    @GetMapping("/getBuyRecordById")
    public CommonResult getBuyRecordById(@RequestParam(value = "productId") Integer productId) {
        return CommonResult.success(productService.getBuyRecordById(productId));
    }

    /**
     * 获取专区的新品推荐和广告图
     *
     * @return
     */
    @GetMapping("/getNewProductsAndBanner")
    public CommonResult getNewProductsAndBanner(@RequestParam(value = "specialId") Integer specialId) {
        return CommonResult.success(productService.getNewProductsAndBanner(specialId));
    }

    /**
     * 获取专区的新品推荐和广告图(new 直接通过专区id找商品)
     *
     * @return
     */
    @GetMapping("/getNewProductsAndBannerNew")
    public CommonResult getNewProductsAndBannerNew(@RequestParam(value = "specialId") Integer specialId) {
        return CommonResult.success(productService.getNewProductsAndBannerNew(specialId));
    }

    @GetMapping("/getList")
    public CommonResult getList(@RequestParam(value = "pageNum", required = false, defaultValue = "1") Integer pageNum,
                                 @RequestParam(value = "pageSize", required = false, defaultValue = "20") Integer pageSize,
                                 @RequestParam(required = false) String productName) {
        return productService.getList(pageNum, pageSize, productName);
    }

    @GetMapping("/specialProductList")
    public CommonResult getList (@RequestParam Integer pageNum,
                                 @RequestParam Integer pageSize,
                                 @RequestParam Integer specialId,
                                 @RequestParam(value = "activityType",required = false) String activityType,
                                 @RequestParam(value = "consumerPower",defaultValue = "",required = false) String consumerPower) {
        String platformData=TokenUtil.getPlatformData();
        List<ProductResponse> list = productService.getSpecialProductList(pageNum, pageSize, specialId,activityType,platformData,consumerPower);
        return CommonResult.page(list);
    }

    /**
     * 根据系统配置key 获取商品
     * @param key
     * @return
     */
    @GetMapping("/configProductList")
    public CommonResult getList (@RequestParam(required = false,defaultValue = "CARD_KERNEL") String key) {
        List<ProductResponse> list = productService.getConfigProductList(key);
        return CommonResult.success(list);
    }


    /**
     * 根据分类Id查询商品列表
     * @param request{type: 默认值："COMPOSITE"，按销量排序："VOLUME"，按价格降序："PRICE_MAX" ，按价格升序"PRICE_MIN",查0元测评商品"IS_ZERO_PRODUCT，查优惠商品“DISCOUNTS_TRIAL_ACTIVITY”}
     * @return
     */
    @PostMapping("/getProductBySpecial")
    public CommonResult getProductBySpecial(@RequestBody ProductListRequest request) {
        return CommonResult.success(frontCategoryService.getProductListForFrontCategory(request));
    }

    /**
     * 获取分类的好物推荐(根据专区获取新品推荐)
     *
     * @return
     */
    @PostMapping("/getRecommendBySpecialId")
    public CommonResult getRecommendBySpecialId(@RequestBody ProductListRequest request) {
        return CommonResult.success(productService.getNewProductsAndBannerNewWay2(request));
    }

    @GetMapping("/getHighestVolumeProduct")
    public CommonResult getHighestVolumeProduct(){
        return productService.getHighestVolumeProduct();
    }

    /**
     * 通过orderId获取供应商放假信息
     */
    @GetMapping("/holidayMsgToMall")
    public CommonResult holidayMsg(@RequestParam Integer orderId){
        OrdersInfoExample ordersInfoExample = new OrdersInfoExample();
        ordersInfoExample.createCriteria().andOrderIdEqualTo(orderId);
        List<OrdersInfo> ordersInfoList = ordersInfoMapper.selectByExample(ordersInfoExample);
        AtomicReference<Boolean> bool = new AtomicReference<>(false);
        ordersInfoList.stream().forEach(item ->{
            Product product = productMapper.selectByPrimaryKey(item.getProductId());
            if (null != product){
                Map<String,String> map = new HashMap<>();
                map.put("bankerId",item.getBankerId().toString());
                String s = HttpClientUtil.doGet(supplyApiConfig.getUrl() + "/banker/holidayMsgToMall",
                        map, supplyApiConfig.getHeadsMap());
                if ("1".equals(s)){
                    bool.set(true);
                }
            }
        });
        Map<String,Object> objectMap = new HashMap<>();
        objectMap.put("isHoliday",bool);
        objectMap.put("recessStartTime",null);
        objectMap.put("recessEndTime",null);
        objectMap.put("deliverTime",null);
        return CommonResult.success(objectMap);
    }

    /**
     * 保存红包发放记录
     * @param productId
     * @return
     */
    @GetMapping("/saveRedpacket")
    public CommonResult saveRedpacket(Integer productId){
        Assert.notNull(productId, "productId不能为空");
        productService.savaRedpacket(productId);
        return CommonResult.success();
    }
}
